package cn.iocoder.yudao.module.member.api.order;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.pojo.ApiCommonResult;
import cn.iocoder.yudao.module.member.controller.app.order.vo.AppMemberCertificateOrderVo;
import cn.iocoder.yudao.module.member.dal.dataobject.order.MemberCertificateOrderDo;
import cn.iocoder.yudao.module.member.dal.redis.no.OrderNoRedisDAO;
import cn.iocoder.yudao.module.member.service.order.CertificateOrderService;
import cn.iocoder.yudao.module.signature.controller.app.application.vo.MemberCertificateOrderDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

@Service
@Validated
@Slf4j
public class CertificateOrderApiImpl implements CertificateOrderApi {
    @Resource
    private CertificateOrderService certificateOrderService;
    @Resource
    private OrderNoRedisDAO orderNoRedisDAO;
    @Override
    public ApiCommonResult<MemberCertificateOrderDto> createOrder(AppMemberCertificateOrderReq appOrderVo) {
        AppMemberCertificateOrderVo req = new AppMemberCertificateOrderVo();
        BeanUtils.copyProperties(appOrderVo, req);
        req.setIsThird("1");
        try {
            //如果是poolType ==2
            MemberCertificateOrderDo order = null;
            if("2".equals(appOrderVo.getPoolType()) ) {
                //先走私有池，再走公共池
                req.setPoolType("1");
                try {
                    order = certificateOrderService.createOrder(req);
                }catch (Exception e){
                    //手动清楚缓存
                    orderNoRedisDAO.deleteKey(appOrderVo.getUdid() + appOrderVo.getUserId());
                    req.setPoolType("0");
                    order = certificateOrderService.createOrder(req);
                }
            }else {
                order = certificateOrderService.createOrder(req);
            }
            if (ObjectUtil.isNull(order)){
                log.error("创建订单失败");
                return ApiCommonResult.error("创建失败");
            }
            return ApiCommonResult.success(BeanUtil.toBean(order,MemberCertificateOrderDto.class));
        } catch (ServiceException | IllegalArgumentException e) {
            log.error("创建订单失败", e);
            return ApiCommonResult.error(e.getMessage());
        } catch (Exception e) {
            log.error("创建订单失败", e);
            return ApiCommonResult.error("创建订单失败");
        }

    }

}
